from fastapi import APIRouter, Depends
from sqlmodel import Session
from crud import role as role_crud
from common import response_code
import models
from dependencies import engine, SessionDep
from typing import Annotated, List, Optional
from routers.auth import get_current_sys_user

router = APIRouter()

"""查询角色

Keyword arguments:
skip -- 起始位置(default 0)
limit -- 每页数量(default 20)
name -- 角色名称
code -- 角色编码
Return: response -- 响应体
"""


@router.get(
    "/api/system/role/",
    tags=["角色管理"],
    summary="查询角色",
    response_model=models.RespJsonRole,
)
async def get_role(
    skip: int = 0,
    limit: Optional[int] = 20,
    name: str | None = None,
    code: str | None = None,
    is_active: bool | None = None,
    user: Annotated[models.SystemUser, Depends(get_current_sys_user)] = None,
    session: SessionDep = Session(engine),
    response: models.RespJsonRole = Depends(response_code.RespSuccessJson.resp_200),
):
    content = role_crud.get_role(skip, limit, name, code, is_active, user, session)

    response.data = {
        "total": content[1],
        "totalPages": 1 if not limit else (content[1] // limit + 1 if content[1] % limit else content[1] // limit),
        "items": [dict(item) for item in content[0]] if content[0] else [],
    }

    return response


"""新增角色

Keyword arguments:
role -- 新增角色参数
Return: response -- 响应体
"""


@router.post(
    "/api/system/role/",
    tags=["角色管理"],
    summary="新增角色",
    response_model=models.RespJsonRole,
)
async def create_role(
    role: models.SystemRoleCreate,
    user: Annotated[models.SystemUser, Depends(get_current_sys_user)],
    session: SessionDep = Session(engine),
    response: models.RespJsonRole = Depends(response_code.RespSuccessJson.resp_201),
):
    role_crud.create_role(role, user)
    response.msg = "新增成功"
    return response


"""编辑角色

Keyword arguments:
id -- 角色id
role -- 编辑角色参数
Return: response -- 响应体
"""


@router.put(
    "/api/system/role/{id}",
    tags=["角色管理"],
    summary="编辑角色",
    response_model=models.RespJsonRole,
)
async def update_role(
    id: int,
    role: models.SystemRoleUpdate,
    user: Annotated[models.SystemUser, Depends(get_current_sys_user)],
    session: SessionDep = Session(engine),
    response: models.RespJsonRole = Depends(response_code.RespSuccessJson.resp_202),
):
    role_crud.update_role(id, role, user, session)
    response.msg = "编辑成功"
    return response


"""删除角色及其关联的菜单关系表

Keyword arguments:
id -- 角色id
Return: response -- 响应体
"""


@router.delete(
    "/api/system/role/",
    tags=["角色管理"],
    summary="删除角色",
    response_model=models.RespJsonRole,
)
async def delete_role(
    ids: List[int],
    user: Annotated[models.SystemUser, Depends(get_current_sys_user)],
    session: SessionDep = Session(engine),
    response: models.RespJsonRole = Depends(response_code.RespSuccessJson.resp_204),
):
    for id in ids:
        role_crud.delete_role(id, user, session)
    response.msg = "删除成功"
    return response